package com.simblog.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.simblog.common.constants.Constants;
import com.simblog.common.utils.FileInfo;

@Controller
@RequestMapping("file/file_upload")
public class FileUploadController extends BaseController {
	private final static Logger logger = LoggerFactory.getLogger(FileUploadController.class);

	@Value("#{configProperties['file.storage.base.dir']}")
	private String basePath;
	@Value("#{configProperties['img.server.url']}")
	private String imgUrl;

	@RequestMapping("upload_image")
	public void headImgUpload(HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {

		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());

		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

			Iterator<String> iterator = multipartHttpServletRequest.getFileNames();
			while (iterator.hasNext()) {
				MultipartFile file = multipartHttpServletRequest.getFile(iterator.next().toString());
				if (file != null) {
					String fileName = file.getOriginalFilename();// 原始文件名
					String fileExt = null; // 文件后缀
					if (fileName != null && !"".equals(fileName)) {// 判空
						if (fileName.lastIndexOf(".") != -1) {// 存在 "."
							fileExt = fileName.substring(fileName.lastIndexOf("."), fileName.length());
						} else {
							response.getWriter()
									.write(assemblyJson(null, Constants.FILE_EXT_EXCEPTION, "文件格式异常").toString());
							;
						}
					} else {
						response.getWriter().write(assemblyJson(null, Constants.FILE_EXT_ERROR, "文件异常").toString());
					}
					String randomFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
							+ fileExt.toLowerCase();
					String path = basePath + randomFileName;
					file.transferTo(new File(path));

					FileInfo fileInfo = new FileInfo();
					fileInfo.setFileName(fileName);
					fileInfo.setRandomFileName(randomFileName);
					fileInfo.setFileUrl(imgUrl + randomFileName);

					response.getWriter()
							.write(assemblyJson(fileInfo, Constants.FILE_UPLOAD_SUCCESS, "文件上传成功").toString());
				}
			}
		} else {
			response.getWriter().write(assemblyJson(null, Constants.FILE_UPLOAD_FAIL, "文件上传失败").toString());
		}
	}

}
